#include <SDL.h>
#include <assert.h>
#include "SDLSurfaceCache.h"

CSDLSurfaceCache::CSDLSurfaceCache()
{
}

void CSDLSurfaceCache::Init(SurfaceCacheInitEntry_t* pInitTable)
{	
	assert(pInitTable != 0);
		
	int CacheCount = 0;
	
	if (pInitTable)
	{
		while( (pInitTable->SurfaceNumber != 0) && (pInitTable->GraphicName != 0) )
		{
			LoadBmpSurface(pInitTable->SurfaceNumber,pInitTable->GraphicName);
			pInitTable++;
			CacheCount++;
		}
	}
	
	printf("CSDLSurfaceCache::CSDLSurfaceCache - %i in cache\n",CacheCount);
}

CSDLSurfaceCache::~CSDLSurfaceCache()
{
	for (IntSurfaceMap::iterator iter = m_SurfaceMap.begin() ; iter != m_SurfaceMap.end() ; iter++)
	{
		if (iter->second != 0)
		{
			// explicitly cleanup surfaces before SDL map goes out of scope
			SDL_FreeSurface(iter->second);
			iter->second = 0;
		}
	}
}

int CSDLSurfaceCache::LoadBmpSurface(int SurfaceNumber,const char* pGraphicImagePath)
{
	// attempt to load surface - if it succeeds optimize and catalog it
	SDL_Surface* pLoad = SDL_LoadBMP(pGraphicImagePath);
	assert(pLoad!=0);
	if(pLoad != NULL)
	{
		// set transparency
		Uint32 colorkey = SDL_MapRGB( pLoad->format, 0, 162, 232);
		SDL_SetColorKey( pLoad, SDL_SRCCOLORKEY, colorkey);
		
		// create optimized graphic for display
		SDL_Surface* pOptimized = SDL_DisplayFormat(pLoad);
		SDL_FreeSurface(pLoad);
		
		assert(pOptimized!=0);
		if (pOptimized != 0)
		{
			// lifetime of surface will be controlled by cache object
			m_SurfaceMap.insert(IntSurfaceMap::value_type(SurfaceNumber,pOptimized));
			return 0;
		}

	}
	
	return -1;
}

SDL_Surface* CSDLSurfaceCache::GetSurface(int SurfaceNumber)
{
	IntSurfaceMap::iterator iter = m_SurfaceMap.find(SurfaceNumber);
	if (iter != m_SurfaceMap.end())
	{
		return iter->second;
	}
	else
	{
		return 0;
	}
}
	
